<template>
	<div>
		<Tabs>
			<TabPane label="会员列表">
				<SuperTable
			    	ref="table"
			    	path="API_MEMBER_LISTS"
			    	:columns="columns"
			    	:params="params"
			    	:loading="false"
			    	@on-selection-change="handleChangeSelection"
			    >
			    	<Form slot="header-right" :model="filterForm" inline @submit.native.prevent>
			    		<FormItem label="按分组">
			    			<Select v-model="filterForm.group_id" style="width: 158px;">
			    				<Option :value="0">全部</Option>
			    				<Option v-for="item in groupLists" :key="item.id" :value="item.id">{{ item.name }}</Option>
			    			</Select>
			    		</FormItem>
		                <FormItem label="按等级">
		                	<Select v-model="filterForm.group_ext_id" style="width: 158px;">
		                		<Option :value="0">全部</Option>
			    				<Option v-for="item in rankLists" :key="item.id" :value="item.id">{{ item.name }}</Option>
			    			</Select>
		                </FormItem>
		                <FormItem label="关键词">
		                    <Input v-model="filterForm.keywords" placeholder="请输入会员名/手机号搜索" suffix="ios-search" clearable style="width: 240px"></Input>
		                </FormItem>
		                <Button type="primary" @click="handleSearch">筛选</Button>
			    	</Form>
			    	
			    	<div slot="page-left">
			    		<Button @click="handleBatchFn('lock')">锁定</Button>
			    		<Button @click="handleBatchFn('unlock')">解锁</Button>
			    		<Button @click="handleBatchFn">批量调整</Button>
			    	</div>
			    	
			    	<div class="ui-table-cell ui-flex" slot-scope="{ row }" slot="user">
			    		<ImageCell :src="row.avatar"></ImageCell>
			            <div class="ui-flex-full" style="margin-left: 10px;">
			            	<p class="ui-ellipsis">{{ row.username }}</p>
			            	<div style="margin-top: 5px;">
			            		<PoptipTable :columns="addressColumns" :data="row.address" placement="right-start" :width="550">
				        			<Button size="small">查看收货地址</Button>
				        		</PoptipTable>
			            	</div>
			            </div>
			        </div>
			        <div class="ui-table-cell" slot-scope="{ row }" slot="info">
		        		<p class="ui-table-cell-line">等级：{{ row.grade ? row.grade.name : '--' }}</p>
		            	<p class="ui-table-cell-line">手机：{{ row.mobile }}</p>
			        </div>
			        <div class="ui-table-cell" slot-scope="{ row }" slot="time">
		        		<p class="ui-table-cell-line">注册时间：{{ handleFormatDate(row.register_time, 'yyyy-MM-dd hh:mm:ss') }}</p>
		            	<p class="ui-table-cell-line">最近消费：{{ handleFormatDate(row.login_time, 'yyyy-MM-dd hh:mm:ss') }}</p>
			        </div>
			        <div class="ui-table-cell" slot-scope="{ row }" slot="money">
		        		<p class="ui-table-cell-line">可用余额：{{ row.money }} ({{ row.frozen_money }} 冻结)</p>
		            	<p class="ui-table-cell-line">会员积分：{{ row.integral }} ({{ row.integral }} 冻结)</p>
			        </div>
			        <div slot-scope="{ row }" slot="action">
			        	<Button type="primary" size="small" @click="handleGoEdit(row)">编辑</Button>
		        		<Poptip
					        confirm
					        transfer
					        placement="left"
					        title="是否确认删除此会员？"
					        @on-ok="handleDelete(row.id)"
					    >
					        <Button type="error" size="small">删除</Button>
					    </Poptip>
					    <Poptip
					        confirm
					        transfer
					        placement="left"
					        title="是否确定重置密码？"
					        @on-ok="handleResetPassword(row.id)"
					    >
					        <Button type="warning" size="small">重置密码</Button>
					    </Poptip>
			        </div>
			    </SuperTable>
			</TabPane>
		</Tabs>
	    
	    <DrawerForm v-model="showBatchModifyModal" title="批量调整" @on-ok="handleBatchModify">
	    	<Form ref="batchform" :model="batchForm" :rules="batchRules" label-position="top" @submit.native.prevent>
	    		<FormItem label="余额">
	    			<Input v-model="batchForm.money" number>
				        <Select v-model="batchForm.money_type" slot="prepend" style="width: 80px">
				            <Option :value="1">增加</Option>
				            <Option :value="0">减少</Option>
				        </Select>
				    </Input>
	    		</FormItem>
	    		<FormItem label="等级">
	    			<Select v-model="batchForm.grade">
	    				<Option v-for="item in rankLists" :key="item.id" :value="item.id">{{ item.name }}</Option>
	    			</Select>
	    		</FormItem>
	    		<FormItem label="分组">
	    			<Select v-model="batchForm.group">
	    				<Option v-for="item in groupLists" :key="item.id" :value="item.id">{{ item.name }}</Option>
	    			</Select>
	    		</FormItem>
	    		<FormItem label="变更日志" prop="log">
	    			<Input v-model="batchForm.log" type="textarea" :rows="5" />
	    		</FormItem>
	    	</Form>
	    </DrawerForm>
	    
	    <DrawerForm v-model="showEditModal" title="批量调整分组 " @on-ok="handleBatchModifyGroup">
	    	<Form ref="editform" :model="editForm" :rules="editRules" label-position="top" @submit.native.prevent>
	    		<FormItem label="手机号" prop="mobile">
	    			<Input v-model="editForm.mobile"></Input>
	    		</FormItem>
	    		<FormItem label="会员等级">
	    			<Select v-model="editForm.grade">
	    				<Option v-for="item in rankLists" :key="item.id" :value="item.id">{{ item.name }}</Option>
	    			</Select>
	    		</FormItem>
	    		<FormItem label="余额">
	    			<Input v-model="editForm.money" number>
				        <Select v-model="editForm.money_type" slot="prepend" style="width: 80px">
				            <Option :value="1">增加</Option>
				            <Option :value="0">减少</Option>
				        </Select>
				    </Input>
	    		</FormItem>
	    		<FormItem label="变更日志" prop="log">
	    			<Input v-model="batchForm.log" type="textarea" :rows="5" />
	    		</FormItem>
	    	</Form>
	    </DrawerForm>
	</div>
</template>

<script>
import Util from '@/libs/util.js';
import Tools from '@/libs/tools.js';
import SuperTable from '@/components/SuperTable.vue';
import ImageCell from '@/components/ImageCell/index.vue';
import PoptipTable from '@/components/PoptipTable.vue';
import DrawerForm from '@/components/DrawerForm.vue';
export default {
	name: 'member',
	components: {
		SuperTable,
		ImageCell,
		PoptipTable,
		DrawerForm,
	},
	data() {
		return {
			ids: [],
			showBatchModifyModal: false,
			showEditModal: false,
			rankLists: [],
			groupLists: [],
			filterForm: {
				keywords: '',
				group_id: 0,
				group_ext_id: 0
			},
			params: {
				keywords: '',
				group_id: '',
				group_ext_id: '',
				page: 1,
				limit: 10,
				relations: ['address', 'grade']
			},
			columns: [
				{
                    type: 'selection',
                    width: 54,
                    align: 'center'
                },
                {
                    title: '会员名',
                    slot: 'user',
                    minWidth: 200
                },
                {
                    title: '等级&手机',
                    slot: 'info',
                    minWidth: 160
                },
                {
                    title: '用户活跃',
                    slot: 'time',
                    minWidth: 220
                },
                {
                    title: '会员资金',
                    slot: 'money',
                    minWidth: 150
                },
                {
                    title: '操作',
                    slot: 'action',
                    align: "center",
                    width: 188
                },
			],
			addressColumns: [
                {
                    title: "收货人",
                    key: "name",
                    width: 90
                },
                {
                    title: "联系电话",
                    key: "mobile",
                    width: 130
                },
                {
                    title: "地址",
                    key: "address",
                    render: (h, params) => {
                    	let address = '';
                    	if(params.row.district_info) {
                    		let districts = [];
                    		districts = params.row.district_info.split(',');
                    		districts.reverse();
                    		address = districts.join(' ') +' '+ params.row.address;
                    	}else{
                    		address = params.row.address;
                    	}
                    	return h('span', address);
                    }
                }
            ],
            batchForm: {
            	money: 0,
            	money_type: 1,
            	grade: null,
            	group: null,
            	log: ''
            },
            batchRules: {
            	log: [
            		{required: true, message: '请填写变更日志', trigger: 'blur'}
            	]
            },
            editForm: {
            	mobile: '',
            	grade: null,
            	money: 0,
            	money_type: 1,
            	log: ''
            },
            editRules: {
            	mobile: [
            		{required: true, message: '请填写会员手机号码', trigger: 'blur'}
            	],
            	log: [
            		{required: true, message: '请填写变更日志', trigger: 'blur'}
            	]
            }
		}
	},
	mounted() {
		this.init();
	},
	methods: {
		init() {
			// 获取分组列表
			Util.ajax.post(this.API['API_MEMBER_GROUP_LISTS'], {page: false, limit: false, order: 0}).then(res => {
				this.groupLists = res;
			}).catch(() => {
				
			})
			
			// 获取等级列表
			Util.ajax.post(this.API['API_MEMBER_GRADE_LISTS'], {page: false, limit: false, order: 0}).then(res => {
				this.rankLists = res;
			}).catch(() => {
				
			})
		},
		// 搜索
		handleSearch() {
			this.params.group_id = this.filterForm.group_id || '';
			this.params.group_ext_id = this.filterForm.group_ext_id || '';
			this.params.keywords = this.filterForm.keywords;
			this.params.page = 1;
		},
		// 表格选中触发事件
		handleChangeSelection(selection) {
			this.ids = selection.map(item => {
				return item.id;
			})
		},
		handleFormatDate(time, format) {
			format = format || 'yyyy-MM-dd';
			if(!time) return '--';
			return Tools.formatDate(time * 1000, format)
		},
		// 删除
		handleDelete(id) {
			Util.ajax.post(this.API['API_MEMBER_DESTROY'], {id: id}).then(res => {
				this.$Message.success('删除成功');
			}).catch(() => {
				
			})
		},
		// 编辑
		handleGoEdit(row) {
			this.$router.push({name: 'user_retail_user_edit', query: {id: row.id }});
		},
		// 重置密码
		handleResetPassword(id) {
			let password = '';
			let seed = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9']; // 数组
  			for(let i = 0; i < 6; i++) {
  				let index = Math.floor(Math.random() * seed.length);
			    password += seed[index];
  			}
			Util.ajax.post(this.API['API_MEMBER_RESET_PASSWORD'], {id: id, password: password}).then(res => {
				this.$Message.info({
                    content: '密码已重置为 “'+ password +'”，请牢记',
                    duration: 0,
                    closable: true
                });
			}).catch(() => {
				
			})
		},
		// 批量操作
		handleBatchFn(type) {
			if(this.ids.length == 0) {
				this.$Message.error("请至少选择一个会员");
				return false;
			}
			// 批量锁定、解锁
			if(type == 'lock' || type == 'unlock') {
				let lock = (type == 'lock' ? 1 : 0)
				Util.ajax.post(this.API['API_MEMBER_LOCK'], {islock: lock, member_ids: this.ids.join(',')}).then(res => {
					this.$Message.success('操作成功');
					this.$refs.table.init();
				})
			}else{
				this.showBatchModifyModal = true; // 批量调整
			}
		},
		// 批量修改
		handleBatchModify() {
			this.$refs.batchform.validate((valid) => {
				if(valid) {
					
				}
			})
		},
		// 批量修改余额
		handleBatchModifyGroup() {
			this.showEditModal = false;
		}
	}
}
</script>